﻿using System.IO;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using LuckyCoding.Models;
using Newtonsoft.Json;

namespace LuckyCoding.Views;

public partial class DispositionView : Window
{
    public DispositionView()
    {
        InitializeComponent();
        OrderBox = this.FindControl<TextBox>("OrderBox");
        IsRunningBox = this.FindControl<CheckBox>("IsRunningBox");
        IsUsePathBox = this.FindControl<CheckBox>("IsUsePathBox");
    }

    private void InitializeComponent()
    {
        AvaloniaXamlLoader.Load(this);
    }

    private void CancelClick(object? sender, RoutedEventArgs e)
    {
        Close(default(DispositionModel));
    }

    private void OkClick(object? sender, RoutedEventArgs e)
    {
        if (string.IsNullOrEmpty(OrderBox.Text) || IsRunningBox.IsChecked == null ||
            IsUsePathBox.IsChecked == null) return;
        Close(new DispositionModel()
        {
            RunOrder = OrderBox.Text
        });
    }

    private async void ImportClick(object? sender, RoutedEventArgs e)
    {
        var dialog = new OpenFileDialog();
        var result = await dialog.ShowAsync(this);
        if (result == null || result.Length == 0) return;
        var model = JsonConvert.DeserializeObject<DispositionModel>(await File.ReadAllTextAsync(result[0]));
        if(model is null)return;
        OrderBox.Text = model.RunOrder;
    }
}